package com.example.epic.controller;

import com.example.epic.common.ResponseData;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URL;

@RestController
public class FileController {

    @GetMapping("/download")
    public String downloadFile(HttpServletRequest request, HttpServletResponse response, @RequestParam String fileName) {
        if (fileName != null) {
            //设置文件路径
            File file = new File("D:\\projects\\lab\\pythonWeb\\" + fileName);

            if (file.exists()) {

                response.reset();
                response.setContentType("application/force-download");// 设置强制下载不打开
                response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);// 设置文件名

                byte[] buffer = new byte[1024];
                FileInputStream fis = null;
                BufferedInputStream bis = null;
                try {
                    fis = new FileInputStream(file);
                    bis = new BufferedInputStream(fis);
                    OutputStream os = response.getOutputStream();
                    int n = bis.read(buffer);
                    while (n != -1) {
                        os.write(buffer, 0, n);
                        // 这里必须刷新流，否则会提示页面找不到
                        os.flush();
                        n = bis.read(buffer);
                    }
                    return "下载成功";
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (bis != null) {
                        try {
                            bis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
        return "下载失败";
    }

    // 复杂文件用@RequestPart，这个注解的值指的是form表单里面的name属性，必须要带有。如果是多文件上传，postman里面的文件的名字都要填写file。
    @PostMapping("/upload")
    public ResponseData uploadFile(@RequestPart("file") MultipartFile[] multipartFiles){
        String rootPath = "D:\\projects\\lab\\pythonWeb\\";

        File fileDir = new File(rootPath);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        try {
            if (multipartFiles != null && multipartFiles.length > 0) {
                for(int i = 0; i < multipartFiles.length; i++){
                    try {
                        System.out.println(multipartFiles[i]);
                        //以原来的名称命名,覆盖掉旧的
                        String storagePath = rootPath+multipartFiles[i].getOriginalFilename();

                        // 第一种
//                        multipartFiles[i].transferTo(new File(storagePath));
                        // 第二种
                        Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
                        // 第三种
                        // Path path = Paths.get(storagePath);
                        //Files.write(path,multipartFiles[i].getBytes());
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            else {
                return ResponseData.fail("文件null");
            }
        } catch (Exception e) {
            return ResponseData.fail(e.getMessage());
        }
        return ResponseData.success("上传成功!");
    }


/*
    @PostMapping("/upload")
    public ResponseData uploadFile(@RequestParam("file") MultipartFile multipartFile){
//        String rootPath = "D:\\projects\\lab\\pythonWeb\\";
        String rootPath = new File("").getAbsolutePath() + "/xmlDir/";

        File fileDir = new File(rootPath);

        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }

        if(multipartFile == null)
            return ResponseData.fail("文件空");


        try{
            //以原来的名称命名,覆盖掉旧的
            String storagePath = rootPath+multipartFile.getOriginalFilename();
            // 第一种
            multipartFile.transferTo(new File(storagePath));


            // 第二种
            // Streams.copy(multipartFile.getInputStream(), new FileOutputStream(storagePath), true);
            // 第三种
            // Path path = Paths.get(storagePath);
            // Files.write(path,multipartFiles[i].getBytes());

        } catch (Exception e) {
            System.out.println("上传失败");
            return ResponseData.fail("上传失败");
        }
        return ResponseData.success("上传成功!");
    }
*/


    @GetMapping(value = "/testpath")
    @ResponseBody
    public ResponseData testpath() throws IOException {

        File f1 = new File(this.getClass().getResource("/").getPath());
        System.out.println("this.getClass().getResource(\"/\").getPath(): "+f1);

        File f2 = new File(this.getClass().getResource("").getPath());
        System.out.println("this.getClass().getResource(\"\").getPath(): "+f2);

        File directory = new File("");// 参数为空
        String courseFile = directory.getCanonicalPath();
        String absolutePath = directory.getAbsolutePath();
        System.out.println("directory.getCanonicalPath() = "+courseFile);
        System.out.println("directory.getAbsolutePath() = " + absolutePath);


        URL xmlpath = this.getClass().getClassLoader().getResource("");
        System.out.println("this.getClass().getClassLoader().getResource(\"\"): "+xmlpath);

        System.out.println("System.getProperty(\"user.dir\"):" +System.getProperty("user.dir"));

        System.out.println("System.getProperty(\"java.class.path\").split(\";\")[0]: "+System.getProperty("java.class.path").split(";")[0]);

        System.out.println("Thread.currentThread().getContextClassLoader().getResource(\"\").getPath(): "+Thread.currentThread().getContextClassLoader().getResource("").getPath());

        return ResponseData.success();
    }
}
